package entity

import (
	"bili-server/app/cfg"
	"fmt"
	"os"
	"regexp"
	"strconv"
	"strings"
)

type DanMu struct {
	Time uint   `json:"time"`
	Text string `json:"text"`
}

// GetDanMus
// 获取弹幕
// <d p="56804894181157376,0,6134557,1,25,16777215,1635437937,0,9ff89ef">太美了</d>
func GetDanMus(aid string) ([]*DanMu, error) {
	config := cfg.GetConfig()
	data, err := os.ReadFile(fmt.Sprintf("%s/%s/1/%s_1.xml", config.Dir[0], aid, aid))
	if err != nil {
		return nil, err
	}
	matched := regexp.MustCompile(`<d p="\S+">\S+</d>`).FindAllStringSubmatch(string(data), -1)
	var danmu = make([]*DanMu, len(matched))
	var i = 0
	for _, v := range matched {
		s := strings.TrimLeft(v[0], "<d p=\"")
		s = strings.TrimRight(s, "</d>")
		arr := strings.Split(s, "\">")
		if len(arr) == 2 {
			p := strings.Split(arr[0], ",")
			if len(p) == 9 {
				time, _ := strconv.Atoi(p[2])
				danmu[i] = &DanMu{
					Time: uint(time) / 1000,
					Text: arr[1],
				}
				i++
			}
		}

	}
	return danmu[:i], nil
}
